#/bin/local/env python

import logging
import wsgiref.handlers
from google.appengine.ext import webapp

class SimpleRedirectHandler(webapp.RequestHandler):

	plus_chars = ['/', ' ', '%20', '%2520']

	searches = {
		'a':  r'http://www.amazon.com/s?url=search-alias%3Daps&field-keywords=',
		'd':  r'http://dictionary.reference.com/browse/',
		'f':  r'http://www.facebook.com/s.php?q=',
		'g':  r'http://www.google.com/search?btnI=Lucky&q=',
		'gb': r'http://blogsearch.google.com/blogsearch?q=',
		'gi': r'http://www.google.com/images?q=',
		'gm': r'http://maps.google.com/maps?q=',
		'gn': r'http://news.google.com/news?q=',
		'i':  r'http://www.google.com/search?btnI=Lucky&q=site:imdb.com%20',
		'w':  r'http://www.google.com/search?btnI=Lucky&q=site:en.wikipedia.org%20',
		'wd': r'http://www.google.com/search?btnI=Lucky&q=site:de.wikipedia.org%20',
		'wf': r'http://www.google.com/search?btnI=Lucky&q=site:fr.wikipedia.org%20',
		'y':  r'http://www.youtube.com/results?search_query='
	}
	
	defaults = {
		'a':  'Python',
		'd':  'redirection',
		'f':  'Jason+Hall',
		'g':  'google',
		'gb': 'twitter+is+down',
		'gi': 'kittens',
		'gm': 'New+York',
		'gn': 'obama',
		'i':  'The+Great+Escape',
		'w':  "Saint+Peter's+Basilica",
		'wd': 'Berlin',
		'wf': 'Paris',
		'y':  "rickroll'd"
	}

	def get(self):
		path = str(self.request.path)
		search = path.split('/')[1]
		query = ("+".join(str(self.request.path).split('/')[2:]))
		if not query:
			query = self.defaults[search]
		else:
			# replace spaces and others with +s
			for char in self.plus_chars:
				query = query.replace(char, '+')
				
		self.redirect(self.searches[search] + query)

def main():
	app = webapp.WSGIApplication([(r'.*', SimpleRedirectHandler)], debug=True)
	wsgiref.handlers.CGIHandler().run(app)
	
if __name__ == "__main__":
	main()
